<?php

namespace app\webapi\vms\service;

use app\webapi\common\BaseService;
use app\webapi\vms\model\ChannelModel;
use app\webapi\vms\model\SystemChannelModel;
use app\webapi\vms\model\WebsiteModel;
use library\JwtToken;
use library\OWException;
use think\facade\Request;

/**
 * @站点服务类
 */
class WebsiteService extends BaseService
{
    /**
     * @desc 获取网站token
     * @param $owner
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/19-11:06
     */
    public function getToken($owner)
    {
        $website = WebsiteModel::field(['id', 'status', 'current_step'])->where(['owner' => $owner])->find();
        if (empty($website)) {
            //获取主系统网站信息,需要调用主系统的接口
            //检测唯一标识是否合法,此处假定只允许主系统三家公司可以创建网站
            if (!in_array($owner['sign'], ['tx', 'bd', 'wy'])) {
                throw new OWException('主系统唯一标识不合法');
            }
            //TODO
            //网站不存在 生成站点
            $website['id'] = $this->generateDraftWebsite($owner);
        }
        //生成token
        $token = (new JwtToken())->createJwt($website['id']);
        $website_status = 1;
        $website_status_text = '已激活';
        if ($website['status'] == 0) {
            $website_status = 0;
            $website_status_text = '未激活';
        }
        return ['token' => $token, 'website_status' => $website_status, 'website_status_text' => $website_status_text, 'current_step' => $website['current_step']];
    }

    public function getWebAddressList($website_id)
    {
        return [
            ['id' => 1, 'name' => '电脑端地址', 'url' => Request::domain() . 'admin/index/index?template_id=1&type=pc'],
            ['id' => 2, 'name' => '手机端端地址', 'url' => Request::domain() . 'admin/index/index?template_id=1&type=mobile'],
            ['id' => 3, 'name' => '后台管理地址', 'url' => ''],
        ];
    }

    /**
     * @desc 获取栏目树形列表
     * @param $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/12-14:04
     */
    public function getChannelTreeList($website_id)
    {
        //定义查询条件
        $where = ['website_id' => $website_id];
        //指定查询字段
        $fields = ['id', 'name', 'pid', 'root_pid'];
        //查询数据
        $list = ChannelModel::field($fields)->where($where)->select()->toArray();
        //提取系统模板id
        $temp_id_arr = array_column($list, 'root_pid');
        //从系统模板中查询栏目的可编辑权限
        $system_channel_info = SystemChannelModel::field(
            ['id', 'is_editable', 'is_removable', 'is_reproducible']
        )->append(['is_editable_text'])->where(['id' => $temp_id_arr])->select()->toArray();
        $is_editable_arr = array_column($system_channel_info, 'is_editable', 'id');
        $is_removable_arr = array_column($system_channel_info, 'is_removable', 'id');
        $is_reproducible_arr = array_column($system_channel_info, 'is_reproducible', 'id');
        foreach ($list as &$v) {
            $v['is_editable'] = $is_editable_arr[$v['root_pid']] ?? 0;
            $v['is_removable'] = $is_removable_arr[$v['root_pid']] ?? 0;
            $v['is_reproducible'] = $is_reproducible_arr[$v['root_pid']] ?? 0;
            unset($v['root_pid']);
        }
        unset($v);
        //处理数据为树状结构
        $tree_list = listToTree($list, 'id', 'pid');
        //返回数据
        return $tree_list;
    }

    /**
     * @desc 获取网站基本信息
     * @param $website_id
     * @return WebsiteModel|array|mixed|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/12-14:24
     */
    public function getBaseInfo($website_id)
    {
        $fields = [
            'id', 'name', 'logo', 'status', 'copyright', 'seo_title', 'icon', 'seo_keywords', 'seo_desc',
            'language', 'create_time', 'slide_switch_speed', 'slide_switch_interval', 'current_step'
        ];
        $info = WebsiteModel::field($fields)
            ->append(['status_text'])
            ->where(['id' => $website_id])->find();
        if (empty($info)) {
            throw new OWException('获取信息失败', $website_id);
        }
        return $info;
    }

    /**
     * @desc 设置网站基本信息
     * @param $params
     * @return void
     * @author zhaozhiwei
     * @time 2023/12/12-14:25
     */
    public function setBaseInfo($params, $website_id)
    {
        //检测网站是否重名
        $count = WebsiteModel::where(['name' => $params['name']])->count();
        if ($count > 0) {
            throw new OWException('网站名称重复');
        }
        //写入网站信息
        $params['current_step'] = 2;
        (new WebsiteModel())->where(['id' => $website_id])->save($params);
        $params['id'] = $website_id;
        return $params;
    }

    public function setAllInfo($params,$website_id){
        //检测网站是否重名
        $count = WebsiteModel::where(['name' => $params['name']])->count();
        if ($count > 0) {
            throw new OWException('网站名称重复');
        }
        //检测域名是否重复
        if(isset($params['domain_name']) && !empty($params['domain_name'])){
            $domain=WebsiteModel::where(['domain'=>$params['domain']])->find();
            if(!empty($domain)){
                throw new OWException('域名已存在');
            }
        }
        //更新网站信息
        (new WebsiteModel())->where(['id' => $website_id])->save($params);

        $params['id'] = $website_id;
        return $params;
    }

    /**
     * @desc 设置网站基础域名
     * @param $domain_name
     * @param $website_id
     * @return array
     * @author zhaozhiwei
     * @time 2023/12/22-12:49
     */
    public function setBaseDomain($domain_name, $website_id)
    {
        (new WebsiteModel())->where(['id' => $website_id])->save(['domain_name' => $domain_name, 'current_step' => 4]);
        return ['id' => $website_id];
    }

    /**
     * @desc 修改站点状态
     * @param $status
     * @param $website_id
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/12-14:51
     */
    public function changeStatus($status, $website_id)
    {
        $info = WebsiteModel::where(['id' => $website_id])->find();
        if (empty($info)) {
            throw new OWException('站点不存在', $website_id);
        }
        //检测网站名称是否填写
        if (!$info['name']) {
            throw new OWException('请先设置网站名称');
        }
        //检测网站模板是否设置
        if (!$info['template_id']) {
            throw new OWException('请先设置网站模板');
        }
        //检测网站域名是否设置
        if ($info['domain_name']) {
            throw new OWException('请先设置网站模板');
        }
        $data = ['status' => $status];
        if ($status == 1) {
            $data['current_step'] = 5;
        }
        (new WebsiteModel())->where(['id' => $website_id])->update($data);
        return true;
    }

    /**
     * @desc 绑定自定义域名
     * @param $domain_name
     * @param $website_id
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/12-15:03
     */
    public function bindCustomDomain($domain_name, $website_id)
    {
        $info = WebsiteModel::where(['id' => $website_id])->find();
        if (empty($info)) {
            throw new OWException('站点不存在', $website_id);
        }
        (new WebsiteModel())->where(['id' => $website_id])->update(['domain_name' => $domain_name]);
        return true;
    }

    /**
     * @desc 设置备案号
     * @param $domain_record_number
     * @param $website_id
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/12-15:32
     */
    public function setRecordNumber($domain_record_number, $website_id)
    {
        $info = WebsiteModel::where(['id' => $website_id])->find();
        if (empty($info)) {
            throw new OWException('站点不存在', $website_id);
        }
        (new WebsiteModel())->where(['id' => $website_id])->update(['domain_record_number' => $domain_record_number]);
        return true;
    }

    /**
     * @desc 获取域名信息
     * @param $website_id
     * @return WebsiteModel|array|mixed|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/12-15:41
     */
    public function getDomainInfo($website_id)
    {
        $fields = ['id', 'domain_name', 'domain_prefix', 'domain_record_number', 'ssl_status', 'ssl_expiration_time'];
        $info = WebsiteModel::field($fields)
            ->append(['ssl_status_text'])
            ->where(['id' => $website_id])->find();
        if (empty($info)) {
            throw new OWException('站点不存在', $website_id);
        }
        $info['ssl_expiration_status_text'] = '未过期';
        if ($info['ssl_expiration_time'] < time()) {
            $info['ssl_expiration_status_text'] = '已过期';
        }
        return $info;
    }

    /**
     * @desc ssl证书续费
     * @param $website_id
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/12-16:00
     */
    public function sslRenew($website_id)
    {
        //TODO
        WebsiteModel::where(['id' => $website_id])->inc('ssl_expiration_time', 86400 * 360)->update();
        return true;
    }

    /**
     * @desc 域名解析验证
     * @param $website_id
     * @return bool
     * @author zhaozhiwei
     * @time 2023/12/12-16:09
     */
    public function verificationDomain($website_id)
    {
        $info = WebsiteModel::where(['id' => $website_id])->find();
        $domain = $info['domain_prefix'] . $info['domain_name'] . '.com';
        $status = 0;
        if (pingAddress($domain) === true) {
            $status = 1;
        };
        return ['domain' => $domain, 'status' => $status];
    }

    /**
     * @desc 栏目排序
     * @param $json_array
     * @param $website_id
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/13-9:03
     */
    public function sortChannel($json_array, $website_id)
    {
        foreach ($json_array as $v) {
            ChannelModel::where(['id' => $v['id'], 'website_id' => $website_id])->save(['sort' => $v['sort']]);
        }
        return true;
    }

    /**
     * @desc 编辑栏目
     * @param $params
     * @return true
     * @author zhaozhiwei
     * @time 2023/12/13-9:30
     */
    public function editChannel($params, $website_id)
    {
        ChannelModel::where(['website_id' => $website_id, 'id' => $params['id']])->save([
                'name' => $params['channel_name'], 'subtitle' => $params['subtitle']]
        );
        return true;
    }

    /**
     * @desc 获取栏目详情信息
     * @param $params
     * @return ChannelModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author zhaozhiwei
     * @time 2023/12/13-10:01
     */
    public function getChannelInfo($params, $website_id)
    {
        $fields = ['id', 'name', 'subtitle', 'sort', 'create_time'];
        $info = ChannelModel::field($fields)->where(['website_id' => $website_id, 'id' => $params['channel_id']])->find();
        return $info;
    }
}